<?php
namespace app\model;

/**
 * 
 * $sn$
 */


class Poster{


    static function GetSoftblacklist($softblacklist, $nickname, $uid = 0)
    {
        return 1;
    }
    static function Getbanklist($system,$type,$postdata){

        $postdata['server'] = DOMAIN0;
        $api_url =  $system['s']['banklisturl'].$type;

        // Init the CURL session
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);            // No header in the result
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
        curl_setopt($ch, CURLOPT_POST, 1);              // This is a POST request
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

        // Fetch and return content
        $data = curl_exec($ch);
        curl_close($ch);

        // Do something with the result. Here, we echo the long URL
        $data = json_decode( $data ,true);

        //$shorturl = str_replace("http://","",$data->shorturl);
         return $data['message'];
    }
    static function Getblacklistnew($system,$ip,$postdata,$softblacklist,$softwhitelist){

        global $_G;
        $softwhitelist = $softwhitelist.",".$system['s']['whitelist'];
        $softwhitelist = str_replace(",", "|", $softwhitelist );
        $nickname = $postdata['nickname'];
        $whitelist = explode("|","|".$softwhitelist );
        if (!empty($whitelist) && $_G['address']['province']!='广东'){
            foreach ($whitelist as $key => $row) {
                if (!empty($row)) {
                    if (strstr($nickname,$row)!==false){
                        return 1;
                    }
                }
            }
        }

        $r = Poster::jiancha($system,$postdata);

        if ($r==1) {
            $blackname = explode("|",$softblacklist);
            if (!empty($blackname)){
                foreach ($blackname as $key => $row) {
                    if (!empty($row)) {
                        if (strstr($nickname,$row)!==false){
                            return 0;
                        }
                    }
                }
            }
            return 1;
        }else{
            return $r;
        }
    }

    static function jiancha($system,$data){
        global $_G;
        // 4同城检查员
        // 3手工白名单
        // 2检查员
        // 1正常
        // 0黑名单、可能同行
        // -1此服务器投诉过
        // -2此链接投诉过
        // -3百分百同行
        // -4同城同行

        $nickname = $data['nickname'];
        $WEIXINXIP = $system['s']['weixinxip'];
        $isname = false;
        $wxname1 = explode(",",$system['s']['wxname1']);
        $wxname2 = explode(",",$system['s']['wxname2']);
        if (in_array($data['nickname'],$wxname1) && strpos($data['ip'],"14.17.22")!==false) {
            $isname = true;
        }
        if (in_array($data['nickname'],$wxname2)) {
            $isname = true;
        }
        if (strpos($data['nickname'],"rdgztest")!==false) {
            $isname = true;
        }
        if (strpos($WEIXINXIP,$data['ip'])!==false || $isname) {
            $data['type'] = 2;
            Poster::savetousu($system,$data);
            if (!empty($data['fromuid'])) {
                db_query("UPDATE ".tablename(t_fans)." SET status = -2 WHERE uid = {$data['fromuid']} and status <> 2");
            } 
            return 2;
        }

        //同服务器投诉过
        if (!empty($data['uid'])) {
            $sql = "SELECT * FROM " . tablename ( t_weixin ) . " 
                        WHERE type = 2 and uid = " . $data['uid'] . " and status <> 2 ";
            $list = db_find ( $sql);
            if (!empty($list)) {
                $data['type'] = -1;
                Poster::savetousu($system,$data);
                return -1;
            }
        }

        //百分百同行
        $sql = "SELECT * FROM " . tablename ( t_blanklist ) . " 
                    WHERE state = '1' and nickname = '" . $nickname . "' ";
        $list = db_find ( $sql);
        if (!empty($list)) {
            $data['type'] = -3;
            Poster::savetousu($system,$data);
            return -3;
        } 

        //同城同行
        $sql = "SELECT * FROM " . tablename ( t_blanklist ) . " 
                    WHERE state = '2'";
        $list = db_select ( $sql);
        if (!empty($list)) {
            foreach ($list as $key => $row) {
                if (strstr($nickname,$row['nickname'])!==false){
                    $_G['address'] = Poster::getcity($system,$data['ip']);
                    $city = $_G['address'];
                    if (strstr($row['city'],$city['city'])!==false){
                        $data['type'] = -4;
                        Poster::savetousu($system,$data);
                        return -4;
                    }elseif (strstr($row['city'],$city['province'])!==false){
                        $data['type'] = 0;
                        Poster::savetousu($system,$data);
                        return 0;
                    }
                }
            }       
        }

        //可能同行
        $sql = "SELECT * FROM " . tablename ( t_blanklist ) . " 
                    WHERE state = '0'";
        $list = db_select ( $sql);
        if (!empty($list)) {
            foreach ($list as $key => $row) {
                if (strstr($nickname,$row['nickname'])!==false){
                    $data['type'] = 0;
                    Poster::savetousu($system,$data);
                    return 0;
                }
            }       
        }
        $config =   Theme::getConfig($system['themeid']);
        //如果是外省客户则判断是否为同行
        if (strpos(",".$config['province'],$_G['address']['province'])==false) {
            $_G['address'] = Poster::getcity($system,$data['ip']);
            if ($_G['address']['province']=='广东省' && $config['province']!='广东省' ) {
                $data['type'] = 4;
                Poster::savetousu($system,$data);
                return 4;
            }
            if (!empty($_G['address']['city']) && DOMAIN0!="30.yixuan.net") {
                if (strpos(",".$system['s']['rjcity'],$_G['address']['province'])!==false && strpos(",".$system['s']['rjcity'],$_G['address']['city'])!==false){
                    $data['type'] = -4;
                    Poster::savetousu($system,$data);
                    return -4;
                }
            }
        }
        return 1;
    }
    static  function savetousu($system,$data){
        global $_G;
        $fans = db_find("SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = '{$data['fromuid']}'");
        // if ($fans['status'] !=2 ) {
            $wxcity = $_G['address'];
            $city = Poster::getcity($system,$fans['ip']);
            $data2 = array(
                'server' => DOMAIN0,
                'softname' =>  MODULE_NAME, 
                'type' =>  $data['type'], 
                'wxuid' => $data['uid'],
                'wxnickname' => $data['nickname'], 
                'wxavatar' => $data['avatar'], 
                'wxip' => $data['ip'], 
                'wxadd' => $wxcity['province'] .$wxcity['city'],
                'uid' => $data['fromuid'], 
                'nickname' => $fans['nickname'], 
                'avatar' => $fans['avatar'], 
                'status' => $fans['status'], 
                'ip' => $fans['ip'], 
                'add' => $city['province'] .$city['city'],
                'domain' => $_SERVER['HTTP_HOST'],
                'url' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'], 
                'addtime' => TIMESTAMP, 
                'autoadd' => 1,
                 );
            // $sql = "SELECT * FROM " . tablename ( t_weixin ) . " 
            //     WHERE softname = '" . MODULE_NAME. "' and wxuid = '" . $data['uid']. "' and uid = '" . $data['fromuid']. "'";
            // $cash = db_find($sql);
            // if (empty($cash)) {
             $r = $insertid = db_insert(t_weixin,$data2);
            // }else{
            //     $r = db_update(t_weixin,$data2,array('id' =>$cash['id']));
            // }
            Poster::Getbanklist($system,'addtousu',$data2);
        // }
    }

    static  function getcity($system,$ip){
        //http://api.map.baidu.com/location/ip?ak=qphDLLsbk0PG220oviyeNxcvKnV75PMa&coor=bd09ll&ip=
        $api_url = $system['s']['ippage'].$ip;
        // $json = json_decode(file_get_contents($api_url));
        // $result['city'] = ($json->content->address_detail->city);//市
        // $result['province'] = ($json->content->address_detail->province);//省

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);            // No header in the result
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
        curl_setopt($ch, CURLOPT_POST, 1);              // This is a POST request
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

        // Fetch and return content
        $data = curl_exec($ch);
        curl_close($ch);

        // Do something with the result. Here, we echo the long URL
        $data = json_decode( $data ,true);

        //$shorturl = str_replace("http://","",$data->shorturl);
        
        $result['city'] = $data['content']['address_detail']['city'];
        $result['province'] = $data['content']['address_detail']['province'];
        return $result;
    }

    static function Getblacklist($system,$ip,$postdata,$softblacklist,$softwhitelist){

        $api_url = $system['s']['banklisturl'].'a';
        $postdata['server'] = DOMAIN0;
        $postdata['softname'] = MODULE_NAME;
        
            
        $postdata = http_build_query($postdata); 
         
        //$postdata = http_build_query($data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 3 // 超时时间（单位:s）
            )
        );
        
        $iphtml = true;
        try {
            $context = stream_context_create($options);
            
            $data = file_get_contents($api_url, false, $context);
        }catch (Exception $e) {
            $iphtml =FALSE;
        }
        if ($iphtml==FALSE || empty($data)){
            $data = "{\"message\":1,\"redirect\":\"\",\"type\":\"ajax\"}";
        }
        // // Init the CURL session
        // $ch = curl_init();
        // curl_setopt($ch, CURLOPT_URL, $api_url);
        // curl_setopt($ch, CURLOPT_HEADER, 0);            // No header in the result
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
        // curl_setopt($ch, CURLOPT_POST, 1);              // This is a POST request
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

        // // Fetch and return content
        // $data = curl_exec($ch);
        // curl_close($ch);

        // // Do something with the result. Here, we echo the long URL
        $data = json_decode( $data ,true);


        if (strpos($system['s']['weixinxip'],$ip)!==false) {
            return 2;
        }

        //$shorturl = str_replace("http://","",$data->shorturl);
        if (intval($data['message'])==1) {
            $blackname = explode("|",$softblacklist);
            if (!empty($blackname)){
                foreach ($blackname as $key => $row) {
                    if (!empty($row)) {
                        if (strstr($nickname,$row)!==false){
                            return 0;
                        }
                    }
                }
            }
            return 1;
        }else{
            return $data['message'];
        }
    }
    static function softpandun($severurl, $softname){
        $data = array('softname' => $softname);
        $info = Poster::softpost($severurl . 'themepandun' ,$data);
        if ($info['error']==1) {
            return_msg($info['msg']);
        }
        return $info;
    }

    static function softfirst($severurl, $softname){
        $data = array('softname' => $softname);
        $info = Poster::softpost($severurl . 'themefirst' ,$data);
        if ($info['error']==1) {
            return_msg($info['msg']);
        }
        return $info;
    }

    // static function softcopytable($severurl, $softname, $tablename,$fieldnames ){
    //     $count =10000;
    //     $i = 1;
    //     while ($count ==10000) {
    //         $count = Poster::softcopy($severurl, $softname, $tablename,$fieldnames,$i );
    //         $i++;
    //     }
    // }

    static function softcopytable($severurl, $uniacid, $softname, $tablename,$fieldnames,$page=1 ){
        $fieldname = explode(",", $fieldnames);
        $data = array(
            'copytype' => $tablename,
            'uniacid' => $uniacid,
            'softname' => $softname,
            'page' => $page,
        );
        //http://cdn31.yixuanrj.cn/app/index.php?i=2&c=home&a=getdata&do=themecopy&copytype=fans&softname=kk31167"
        $info = Poster::softpost($severurl . 'themecopy' ,$data);
        $list = $info['list'];
        if ($info['error']==0 ) {
            // if ($page == 1 && !empty($fieldnames)) {
            //     foreach ($fieldname as $key => $row) {
            //         if ($row =='workerid' || $row =='uid' || $row =='fromuid' || $row=='parentid') {
            //            db_query("ALTER TABLE ".tablename(MODULE_NAME . "_a" . $tablename)."  ADD COLUMN `" . $row . "_old` int(11) DEFAULT '0';");
            //         }else{
            //             db_query("ALTER TABLE ".tablename(MODULE_NAME . "_a" . $tablename)."  ADD COLUMN `" . $row . "_old` varchar(300) DEFAULT NULL; ");
            //         }
                    
            //     }
            // }
            if ($page==1) {
                db_query("TRUNCATE table " . tablename(MODULE_NAME . "_a" . $tablename));
            }
            if (!empty($list)) {
                if ($tablename=='rea') {
                    db_query("ALTER TABLE ".tablename(MODULE_NAME . "_a" . $tablename)."  MODIFY areaId INT");
                }else{
                    db_query("ALTER TABLE ".tablename(MODULE_NAME . "_a" . $tablename)."  MODIFY id INT");
                }
                foreach ($list as $index => $item) {
                    if ( !empty($fieldnames)) {
                        foreach ($fieldname as $key => $row) {
                            $item[$row.'_old'] = $item[$row];
                        }
                    }
                    $r = $insertid = db_insert(MODULE_NAME . "_a" . $tablename,$item);
                    if (!$r) {
                        echo $softname . "-" . $tablename ."-" . $item['id']. "出错<br>";
                    }
                }
                if ($tablename=='rea') {
                    db_query("ALTER TABLE ".tablename(MODULE_NAME . "_a" . $tablename)."  MODIFY areaId INT AUTO_INCREMENT");
                }else{
                    db_query("ALTER TABLE ".tablename(MODULE_NAME . "_a" . $tablename)."  MODIFY id INT AUTO_INCREMENT");
                }

                // db_query("ALTER TABLE ".tablename(MODULE_NAME . "_a" . $tablename)."  MODIFY id INT");
                // $listchunk = array_chunk($list,100,true);
                // foreach ($listchunk as $index => $item) {
                //     foreach ($item as $index2 => $item2) {
                //         foreach ($fieldname as $key => $row) {
                //             $item2[$row.'_old'] = $item2[$row];
                //         }
                //         if ($index2 == 0 ) {
                //             echo 'index1;';
                //            $itemtemp = $item2;
                //         }else{
                //             echo $index2;
                //            $itemtemp = array_merge_recursive($itemtemp , $item2);
                //         }
                //     }
                //     var_dump($itemtemp);
                //     $r = $insertid = db_insert(MODULE_NAME . "_a" . $tablename,$itemtemp);
                //     exit;
                //     if (!$r) {
                //         echo $softname . "-" . $tablename ."-" . $item['id'] . "出错<br>";
                //     }
                //     // exit;
                // }
                // db_query("ALTER TABLE ".tablename(MODULE_NAME . "_a" . $tablename)."  MODIFY id INT AUTO_INCREMENT");
            }
            echo $softname . "-" . $tablename . "-第" . $page . "页导出完成<br>";
        }else{
            echo $softname . "-" . $tablename . "-第" . $page . "页复制失败<br>";
        }
        return count($list);
    }
    // static function softcopy($severurl, $list, $softname){
    //     $data = array(
    //         'softname' => $softname,
    //         'copytype' => 'config',
    //     );

    //     //关闭自动编号
    //     db_query("ALTER TABLE ".tablename(t_theme)."  MODIFY id INT");
    //     db_query("ALTER TABLE ".tablename(t_config)."  MODIFY id INT");
    //     foreach ($list as $index => $item) {
    //         $data['themeid'] = $item['id'];
    //         $info = Poster::softpost($severurl . 'themecopy' ,$data);
    //         if ($info['error']==0) {
    //             $insertid = db_insert(t_theme,$info['theme']);
    //             $insertid = db_insert(t_config,$info['config']);
    //         }else{
    //             return_msg("复制失败");
    //         }
    //     }
    //     db_query("ALTER TABLE ".tablename(t_theme)."  MODIFY id INT AUTO_INCREMENT");
    //     db_query("ALTER TABLE ".tablename(t_config)."  MODIFY id INT AUTO_INCREMENT");
    //     return;
    // }


    static function softpost($url,$postdata){

        // $postdata['server'] = DOMAIN0;
        $api_url =  $url;

        // Init the CURL session
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);            // No header in the result
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
        curl_setopt($ch, CURLOPT_POST, 1);              // This is a POST request
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

        // Fetch and return content
        $data = curl_exec($ch);
        curl_close($ch);

        // Do something with the result. Here, we echo the long URL
        $data = json_decode( $data ,true);

        //$shorturl = str_replace("http://","",$data->shorturl);
         return $data['message'];
    }


    static function ServerQR($system,$type,$postdata){

        // $postdata['server'] = DOMAIN0;
        $api_url =  $system['s']['qrserverurl'].$type;

        // Init the CURL session
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);            // No header in the result
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
        curl_setopt($ch, CURLOPT_POST, 1);              // This is a POST request
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

        // Fetch and return content
        $data = curl_exec($ch);
        curl_close($ch);

        // Do something with the result. Here, we echo the long URL
        $data = json_decode( $data ,true);

        //$shorturl = str_replace("http://","",$data->shorturl);
         return $data['message'];
    }


    /**
     * 获取短网址，如果获取失败则返回原有网址
     * $url 长网址 $title 标题可为空
     * 返回短网址
     */
    // static function Getyourls($url,$title){

    //     $signature = 'a3606d1dc8';
    //     $api_url =  'http://y0x.cn/yourls-api.php';

    //     // Init the CURL session
    //     $ch = curl_init();
    //     curl_setopt($ch, CURLOPT_URL, $api_url);
    //     curl_setopt($ch, CURLOPT_HEADER, 0);            // No header in the result
    //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
    //     curl_setopt($ch, CURLOPT_POST, 1);              // This is a POST request
    //     curl_setopt($ch, CURLOPT_POSTFIELDS, array(     // Data to POST
    //             //'shorturl' => 'ozh',
    //             'format'   => 'json',
    //             'action'   => 'shorturl',
    //             'signature' => $signature,
    //             'url' => $url,
    //             'title' => $title
    //         ));

    //     // Fetch and return content
    //     $data = curl_exec($ch);
    //     curl_close($ch);

    //     // Do something with the result. Here, we echo the long URL
    //     $data = json_decode( $data );

    //     //$shorturl = str_replace("http://","",$data->shorturl);

    //     $shorturl = $data->shorturl;
    //     if (empty($shorturl)) {
    //         return $url;
    //     }else{
    //         return $shorturl;
    //     }
    // }

    /**
     * 获取短网址，如果获取失败则返回原有网址
     * $url 长网址 $title 标题可为空
     * 返回短网址
     */
    static function GetMainUrl($system,$url,$title){

        $signature = 'a3606d1dc8';
        $api_url =  $system['s']['yxmainurl'];

        // Init the CURL session
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);            // No header in the result
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
        curl_setopt($ch, CURLOPT_POST, 1);              // This is a POST request
        curl_setopt($ch, CURLOPT_POSTFIELDS, array(     // Data to POST
                //'shorturl' => 'ozh',
                'format'   => 'json',
                'action'   => 'shorturl',
                'signature' => $signature,
                'url' => $url,
                'title' => $title
            ));

        // Fetch and return content
        $data = curl_exec($ch);
        curl_close($ch);

        // Do something with the result. Here, we echo the long URL
        $data = json_decode( $data );

        //$shorturl = str_replace("http://","",$data->shorturl);

        $shorturl = $data->shorturl;
        if (empty($shorturl)) {
            return $url;
        }else{
            $txt = substr(MODULE_NAME,0,1);
            $shorturl = str_replace("main",$txt,$shorturl);
            return $shorturl;
        }
    }
    /**
     * 获取短网址，如果获取失败则返回原有网址
     * $url 长网址 $title 标题可为空
     * 返回短网址
     */
    static function GetWorkerUrl($system,$url,$title){

        $signature = 'a3606d1dc8';
        $api_url =  $system['s']['yxworkerurl'];

        // Init the CURL session
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);            // No header in the result
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
        curl_setopt($ch, CURLOPT_POST, 1);              // This is a POST request
        curl_setopt($ch, CURLOPT_POSTFIELDS, array(     // Data to POST
                //'shorturl' => 'ozh',
                'format'   => 'json',
                'action'   => 'shorturl',
                'signature' => $signature,
                'url' => $url,
                'title' => $title
            ));

        // Fetch and return content
        $data = curl_exec($ch);
        curl_close($ch);

        // Do something with the result. Here, we echo the long URL
        $data = json_decode( $data );

        //$shorturl = str_replace("http://","",$data->shorturl);

        $shorturl = $data->shorturl;
        if (empty($shorturl)) {
            return $url;
        }else{
            $txt = substr(MODULE_NAME,0,2);
            $shorturl = str_replace("worker",$txt,$shorturl);
            return $shorturl;
        }
    }
    /**
     * 获取短网址，如果获取失败则返回原有网址
     * $url 长网址 $title 标题可为空
     * 返回短网址
     */
    static function GetPosterUrl($system,$url,$title){

        $signature = 'a3606d1dc8';
        $api_url =  $system['s']['yxposterurl'];

        // Init the CURL session
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);            // No header in the result
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
        curl_setopt($ch, CURLOPT_POST, 1);              // This is a POST request
        curl_setopt($ch, CURLOPT_POSTFIELDS, array(     // Data to POST
                //'shorturl' => 'ozh',
                'format'   => 'json',
                'action'   => 'shorturl',
                'signature' => $signature,
                'url' => $url,
                'title' => $title
            ));

        // Fetch and return content
        $data = curl_exec($ch);
        curl_close($ch);

        // Do something with the result. Here, we echo the long URL
        $data = json_decode( $data );

        //$shorturl = str_replace("http://","",$data->shorturl);

        $shorturl = $data->shorturl;
        if (empty($shorturl)) {
            return $url;
        }else{
            $shorturl = str_replace("poster",MODULE_NAME,$shorturl).'?t='.TIMESTAMP;
            return $shorturl;
        }
    }
    /**
     * 获取短网址，如果获取失败则返回原有网址
     * $url 长网址 $title 标题可为空
     * 返回短网址
     */
    static function GetExampleUrl($system,$url,$title){

        $signature = 'a3606d1dc8';
        $api_url =  $system['s']['yxexampleurl'];

        // Init the CURL session
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);            // No header in the result
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
        curl_setopt($ch, CURLOPT_POST, 1);              // This is a POST request
        curl_setopt($ch, CURLOPT_POSTFIELDS, array(     // Data to POST
                //'shorturl' => 'ozh',
                'format'   => 'json',
                'action'   => 'shorturl',
                'signature' => $signature,
                'url' => $url,
                'title' => $title
            ));

        // Fetch and return content
        $data = curl_exec($ch);
        curl_close($ch);

        // Do something with the result. Here, we echo the long URL
        $data = json_decode( $data );

        //$shorturl = str_replace("http://","",$data->shorturl);

        $shorturl = $data->shorturl;
        if (empty($shorturl)) {
            return $url;
        }else{
            $shorturl = str_replace("example",MODULE_NAME,$shorturl).'?t='.TIMESTAMP;
            return $shorturl;
        }
    }
    static function getById($id) {
        if (empty($id)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_poster) . " where id = :id";
        $row = db_find($sql, array(":id"=>$id));
        return $row;
    }

    static function getByThemeIdnew($themeid,$status=0){
        if (empty($themeid)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename ( t_poster ) . " 
                      WHERE themeid = :themeid and status =:status limit 1";
        $row = db_find( $sql , array(":themeid"=>$themeid,":status"=>$status));
        return $row;
    }

    static function getByThemeId($uniacid,$themeid){
        if (empty($uniacid) ||empty($themeid)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename ( t_poster ) . " 
                      WHERE uniacid = :uniacid and themeid = :themeid  limit 1";
        $row = db_find( $sql , array(":uniacid"=>$uniacid,":themeid"=>$themeid));
        return $row;
    }

    static function getList($uniacid){
        if (empty($uniacid)) {
            return false;
        }
        $sql = "SELECT master.* FROM " . tablename ( t_poster ) . " as master
                      WHERE uniacid = :uniacid and status = 1  ORDER BY master.id desc ";
        $list = db_select ( $sql , array(":uniacid"=>$uniacid));
        return $list;
    }

    static function getUseById($id) {
        if (empty($id)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_p_use) . " where id = :id";
        $row = db_find($sql, array(":id"=>$id));
        return $row;
    }

    static function deleteById($id){
        if (empty($id)) {
            return false;
        }
        db_delete ( t_poster, array ('id' => $id) );
        return true;
    }

    static function deleteUseById($id){
        if (empty($id)) {
            return false;
        }
        db_delete ( t_p_use, array ('id' => $id) );
        return true;
    }

    static function getApplyListByCondition($condition,$pageNumber,$pageSize){
        $sql = "SELECT master.* FROM " . tablename ( t_p_apply ) . " as master
                      WHERE   {$condition} ORDER BY master.id desc
                                    LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
        $list = db_select ( $sql );
        return $list;
    }


    static function getUseListByCondition($condition,$pageNumber,$pageSize){
        $sql = "SELECT master.*,m2.username,m2.mobile,m2.nickname,m2.avatar FROM " . tablename ( t_p_use ) . " as master
                        left join " . tablename (t_distributor) . " as m2 on master.dopenid = m2.openid
                        WHERE   {$condition} ORDER BY master.id desc
                                    LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
        $list = db_select ( $sql );
        return $list;

    }

    static function getUseNumByCondition($condition){
        return db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_p_use ) . " as master
                    left join " . tablename (t_distributor) . " as m2 on master.dopenid = m2.openid
                    WHERE  {$condition} ORDER BY master.id" );
    }

    static function createImage($imgurl){
        //loadload_func('communication');
        $resp = yxcurl($imgurl);
        if (!empty($resp)) {
            return imagecreatefromstring($resp);
        }
        $i = 0;
        while ($i < 3) {
            $resp = yxcurl($imgurl);

            if (!empty($resp)) {
            return imagecreatefromstring($resp);
        }
            ++$i;
        }
        return '';
    }

    static function getRealData($data){
        $data['left'] = intval(str_replace('px', '', $data['left'])) * 2+1;
        $data['top'] = intval(str_replace('px', '', $data['top'])) * 2+2;
        $data['width'] = intval(str_replace('px', '', $data['width'])) * 2+2;
        $data['height'] = intval(str_replace('px', '', $data['height'])) * 2+2;
        $data['size'] = intval(str_replace('px', '', $data['size'])) * 2;
        $data['src'] = tomedia($data['src']);
        return $data;
    }

    static function mergeImage($target, $data, $imgurl){
        $img = self::createImage($imgurl);
        $w = imagesx($img);
        $h = imagesy($img);
        imagecopyresized($target, $img, $data['left'], $data['top'], 0, 0, $data['width'], $data['height'], $w, $h);
        imagedestroy($img);
        return $target;
    }

    static  function mergeText($target, $data, $text){
        $font = PATH_FONT . 'msyhbd.ttf';
        $colors = self::hex2rgb($data['color']);
        $color = imagecolorallocate($target, $colors['red'], $colors['green'], $colors['blue']);
        if ($data['size']<10) {
            $data['size']=25;
        }
        imagettftext($target, $data['size'], 0, $data['left'], $data['top'] + $data['size'], $color, $font, $text);
        return $target;
    }

    static function hex2rgb($colour){
        if ($colour[0] == '#') {
            $colour = substr($colour, 1);
        }

        if (strlen($colour) == 6) {
            list($r, $g, $b) = array($colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5]);
        }
        else if (strlen($colour) == 3) {
            list($r, $g, $b) = array($colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2]);
        }
        else {
            return false;
        }

        $r = hexdec($r);
        $g = hexdec($g);
        $b = hexdec($b);
        return array('red' => $r, 'green' => $g, 'blue' => $b);
    }

    static function uploadImage($img){
        global $_G;

        //loadload_func('communication');
        $weid = $_G['acid'];
        $accObj = WeAccount::create ( $weid );
        $access_token = $accObj->fetch_token ();
        $url = 'http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $access_token . '&type=image';
        $ch1 = curl_init();
        $data = array('media' => '@' . $img);

        if (version_compare(PHP_VERSION, '5.5.0', '>')) {
            $data = array('media' => curl_file_create($img));
        }

        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $data);
        $content = @json_decode(curl_exec($ch1), true);

        if (!is_array($content)) {
            $content = array('media_id' => '');
        }

        curl_close($ch1);
        return $content['media_id'];
    }

    static function createPoster($poster, $member, $qr, $upload = true){
        global $_G;
        $path = IA_ROOT . '/attachment/images/'.MODULE_NAME.'/' . $_G['mpid'] .'/'.$member['themeid']. '/';
        if (!is_dir($path)) {
            //load_func('file');
            mkdirs($path);
        }
        $jmdata = array(
            'openid'  => $member['openid'],
            'bg'      => $poster['bg'],
            'data'    => $poster['data'],
            'version' => 1);
        $md5 = md5(json_encode($jmdata));
        $file = $md5 . '.png';
        if (!is_file($path . $file) || ($qr['qrimg'] != $qr['current_qrimg'])) {
            set_time_limit(0);
            @ini_set('memory_limit', '256M');
            $target = imagecreatetruecolor(640, 1008);
            $bg = self::createImage(tomedia($poster['bg']));
            imagecopy($target, $bg, 0, 0, 0, 0, 640, 1008);
            imagedestroy($bg);
            $data = json_decode(str_replace('&quot;', '\'', $poster['data']), true);

            foreach ($data as $d ) {
                $d = self::getRealData($d);

                if ($d['type'] == 'head') {
                    $avatar = preg_replace('/\\/0$/i', '/96', $member['avatar']);

                    $target = self::mergeImage($target, $d, $avatar);
                }else if ($d['type'] == 'img') {
                    $target = self::mergeImage($target, $d, $d['src']);
                }else if ($d['type'] == 'qr') {
                    $target = self::mergeImage($target, $d, tomedia($qr['current_qrimg']));
                }else if ($d['type'] == 'nickname') {
                    $target = self::mergeText($target, $d, $member['nickname']);
                }

            }

            imagepng($target, $path . $file);
            imagedestroy($target);

            if ($qr['qrimg'] != $qr['current_qrimg']) {
                db_update(t_ewm, array('qrimg' => $qr['current_qrimg']), array('id' => $qr['id']));
            }

        }
        $img = $_G['siteroot'] . '/attachment/images/'.MODULE_NAME.'/' . $_G['mpid'] .'/'.$member['themeid']. '/' . $file;
        if (!$upload) {
            return $img;
        }

        if (($qr['qrimg'] != $qr['current_qrimg']) || empty($qr['mediaid']) || empty($qr['createtime']) || ((($qr['createtime'] + (3600 * 24 * 3)) - 7200) < time())) {
            $mediaid = self::uploadImage($path . $file);
            $qr['mediaid'] = $mediaid;
            db_update(t_ewm, array('mediaid' => $mediaid, 'createtime' => time()), array('id' => $qr['id']));
        }
        return array('img' => $img, 'mediaid' => $qr['mediaid']);
    }

    static function mergeImageavatar($target, $data, $imgurl){
        $img = self::createImage($imgurl);
        $src_img = $img;
        $w = imagesx($img);
        $h = imagesy($img);
        $w=min($w,$h);
        $h= $w;
        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明,并可以设定背景色
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r = $w / 2;    //圆半径
        $y_x = $r;      //圆心X坐标
        $y_y = $r;      //圆心Y坐标
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }
        imagecopyresized($target, $img, $data['left'], $data['top'], 0, 0, $data['width'], $data['height'], $w, $h);
        imagedestroy($img);
        return $target;
    }

    static function createGoodsPoster($poster, $member, $qr, $upload = true){
        global $_G;

        //$path =  IA_ROOT . '/attachment/images/'.MODULE_NAME.'/' . $_G['mpid'] . '/'.$member['themeid'].'/';
        $path = IA_ROOT . '/attachment/images/poster/'. date('Y-m') . '/' . MODULE_NAME.'/';
        if (!is_dir($path)) {
            //load_func('file');
            mkdirs($path);
        }
        $jmdata = array(
            'openid'   => $member['openid'],
            'bg'       => $poster['bg'],
            'themeid'  => $member['themeid'],
            'data'     => $poster['data'],
            'addtime'     => TIMESTAMP,
            'version'  => 1
        );
        $md5 = md5(json_encode($jmdata));
        $file = $md5 . '.jpg';
        //if (!is_file($path . $file)) {
            set_time_limit(0);
            @ini_set('memory_limit', '256M');
            $target = imagecreatetruecolor(640, 1008);
            $bg = self::createImage(tomedia($poster['bg']));
            imagecopy($target, $bg, 0, 0, 0, 0, 640, 1008);
            imagedestroy($bg);
            $data = json_decode(str_replace('&quot;', '\'', $poster['data']), true);

            foreach ($data as $d ) {
                $d = self::getRealData($d);
                if ($d['type'] == 'head' && !empty($member['avatar'])) {
                    $avatar = preg_replace('/\\/0$/i', '/96', $member['avatar']);
                    // $avatar = self::circular_img($avatar);
                    // echo "string" .$avatar;
                    $target = self::mergeImageavatar($target, $d, $avatar);
                }else if ($d['type'] == 'img') {
                    $target = self::mergeImage($target, $d, $d['src']);
                }else if ($d['type'] == 'qr') {
                    $target = self::mergeImage($target, $d, $qr);
                }else if ($d['type'] == 'nickname' && !empty($member['nickname'])) {
                    $target = self::mergeText($target, $d, $member['nickname']);
                }

            }
            imagepng($target, $path . $file);
            imagedestroy($target);

            if (!empty($_G['setting']['remote']['type'])) { // 判断系统是否开启了远程附件
                //load_func('file');
                $posterimg = 'images/poster/'. date('Y-m') . '/' . MODULE_NAME.'/' . $file;
                $remotestatus = file_remote_upload($posterimg); //上传图片到远程
                if (is_error($remotestatus)) { 
                    return_msg('生成海报上传失败!');
                } else {
                    $img = tomedia($posterimg)."/99.jpg";  // 远程图片的访问URL
                    //load_func('file');
                    //if (!is_file($qr)) {
                        //unlink(IA_ROOT . '/attachment/' . $qr);
                    //}
                   // $pathname // 本地要存入库的地址
                } 
            }
        //}
        //$img = $_G['siteroot'] . '/attachment/images/'.MODULE_NAME.'/' . $_G['mpid'] .  '/'.$member['themeid'].'/' . $file;
        if (!$upload) {
            return $img;
        }
        return array('img' => $img);
    }


    static function createFixPoster($poster, $member, $qr, $upload = true){
        global $_G;
        $path = IA_ROOT . '/attachment/images/'.MODULE_NAME.'/fixposter/' . $_G['mpid'] . '/';
        if (!is_dir($path)) {
            //load_func('file');
            mkdirs($path);
        }
        $jmdata = array(
            'openid'  => $member['openid'],
            'useid'  => $member['useid'],
            'bg'      => $poster['bg'],
            'data'    => $poster['data'],
            'version' => 1);
        $md5 = md5(json_encode($jmdata));
        $file = $md5 . '.png';
        if (!is_file($path . $file) || ($qr['qrimg'] != $qr['current_qrimg'])) {
            set_time_limit(0);
            @ini_set('memory_limit', '256M');
            $target = imagecreatetruecolor(640, 1008);
            $bg = self::createImage(tomedia($poster['bg']));
            imagecopy($target, $bg, 0, 0, 0, 0, 640, 1008);
            imagedestroy($bg);
            $data = json_decode(str_replace('&quot;', '\'', $poster['data']), true);

            foreach ($data as $d ) {
                $d = self::getRealData($d);

                if ($d['type'] == 'head' && !empty($member['avatar'])) {
                    $avatar = preg_replace('/\\/0$/i', '/96', $member['avatar']);
                    $target = self::mergeImage($target, $d, $avatar);
                }else if ($d['type'] == 'img') {
                    $target = self::mergeImage($target, $d, $d['src']);
                }else if ($d['type'] == 'qr') {
                    $target = self::mergeImage($target, $d, tomedia($qr['current_qrimg']));
                }else if ($d['type'] == 'nickname' && !empty($member['nickname'])) {
                    $target = self::mergeText($target, $d, $member['nickname']);
                }

            }

            imagepng($target, $path . $file);
            imagedestroy($target);

            if ($qr['qrimg'] != $qr['current_qrimg']) {
                db_update(t_p_ewm_permanent, array('qrimg' => $qr['current_qrimg']), array('id' => $qr['id']));
            }

        }
        $img = $_G['siteroot'] . '/attachment/images/'.MODULE_NAME.'/fixposter/' . $_G['mpid'] . '/' . $file;
        if (!$upload) {
            return $img;
        }

        if (($qr['qrimg'] != $qr['current_qrimg']) || empty($qr['mediaid']) || empty($qr['createtime']) || ((($qr['createtime'] + (3600 * 24 * 3)) - 7200) < time())) {
            $mediaid = self::uploadImage($path . $file);
            $qr['mediaid'] = $mediaid;
            db_update(t_p_ewm_permanent, array('mediaid' => $mediaid, 'createtime' => time()), array('id' => $qr['id']));
        }
        return array('img' => $img, 'mediaid' => $qr['mediaid']);
    }

    static function base64_image_content($base64_image_content){
        global $_G;
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $path = IA_ROOT . '/attachment/images/poster/'. date('Y-m') . '/' . MODULE_NAME . '/' ;
            if (!is_dir($path)) {
                //load_func('file');
                mkdirs($path);
            }
            $new_file = $path;
            $file = time().".{$type}";
            $new_file = $new_file.$file;
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                if (!empty($_G['setting']['remote']['type'])) { // 判断系统是否开启了远程附件
                    //load_func('file');
                    $posterimg = 'images/poster/'. date('Y-m') . '/' . MODULE_NAME.'/' . $file;
                    $remotestatus = file_remote_upload($posterimg); //上传图片到远程
                    if (is_error($remotestatus)) {
                        return $base64_image_content;
                    } else {
                        $img = tomedia($posterimg);  // 远程图片的访问URL
//                        //load_func('file');
                        //if (!is_file($qr)) {
                        //unlink(IA_ROOT . '/attachment/' . $qr);
                        //}
                        // $pathname // 本地要存入库的地址

                        return $img;
                    }
                }
            }else{
                return $base64_image_content;
            }
        }else{
            return $base64_image_content;
        }
    }

static function getFixedTicket($poster, $member, $uniaccount){
        global $_G;
        global $_P;
        $scene_str = md5(MODULE_NAME.':' . $_G['mpid'] . ':'. $member['openid'] . ':' . $member['useid'] . ':' . $poster['id']);
        $bb = '{"action_info":{"scene":{"scene_str":"' . $scene_str . '"} },"action_name":"QR_LIMIT_STR_SCENE"}';
        $token = $uniaccount->fetch_token();
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $token;
        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $bb);
        $c = curl_exec($ch1);
        $result = @json_decode($c, true);

        if (!is_array($result)) {
            return false;
        }
        if (!empty($result['errcode'])) {
            return error(-1, $result['errmsg']);
        }
        $ticket = $result['ticket'];
        return array('barcode' => json_decode($bb, true), 'ticket' => $ticket);
    }


static function getTempTicket($poster, $member, $uniaccount){
        global $_G;
        global $_P;
        $scene_str = md5(MODULE_NAME.':' . $_G['mpid'] . ':' . $member['openid'] . ':' . $member['themeid'] . ':' . $poster['id']);
        $qrcid = db_fetchcolumn("SELECT qrcid FROM ".tablename('qrcode')." 
            WHERE acid = :acid AND model = '1' AND type = 'scene' ORDER BY qrcid DESC LIMIT 1", array(':acid' => $_G['acid']));
        $scene_id = !empty($qrcid) ? ($qrcid + 1) : 100001;
        $bb = '{"expire_seconds": 2592000, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
        $token = $uniaccount->fetch_token();
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $token;
        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $bb);
        $c = curl_exec($ch1);
        $result = @json_decode($c, true);

        if (!is_array($result)) {
            return false;
        }
        if (!empty($result['errcode'])) {
            return error(-1, $result['errmsg']);
        }
        $ticket = $result['ticket'];
        return array('barcode' => json_decode($bb, true), 'ticket' => $ticket);
    }

static  function getAcidTicket($acid, $uniaccount){
        global $_G;
        global $_P;
        $qrcid = db_fetchcolumn("SELECT qrcid FROM ".tablename('qrcode')."
            WHERE acid = :acid AND model = '1' AND type = 'scene' ORDER BY qrcid DESC LIMIT 1", array(':acid' => $acid));
        $scene_id = !empty($qrcid) ? ($qrcid + 1) : 100001;
        $bb = '{"expire_seconds": 2592000, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
        $token = $uniaccount->fetch_token();
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $token;
        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $bb);
        $c = curl_exec($ch1);
        $result = @json_decode($c, true);

        if (!is_array($result)) {
            return false;
        }
        if (!empty($result['errcode'])) {
            return error(-1, $result['errmsg']);
        }
        $ticket = $result['ticket'];
        return array('barcode' => json_decode($bb, true), 'ticket' => $ticket);
    }

    /***
     * 永久
     * @param $poster
     * @param $member
     * @param $keyword
     * @return array
     */
static  function getQR($system,$poster, $member,$keyword){
        global $_G;
        global $_P;
        $acid = $_G['acid'];
        $uniaccount = WeAccount::create($acid);
        $result = self::getFixedTicket($poster, $member, $uniaccount);
        if (is_error($result)) {
            return $result;
        }
        if (empty($result)) {
            return error(-1, '生成二维码失败');
        }
        print_r($result);
        $barcode = $result['barcode'];
        $ticket = $result['ticket'];
        $qrimg = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $ticket;
        $yx_qrcode = array(
            'uniacid'    => $_G['mpid'],
            'acid'       => $_G['acid'],
            'scene_str' => $barcode['action_info']['scene']['scene_str'],
            'model'      => 2,
            'name'       => MODULE_NAME,
            'keyword'    => $keyword,
            'type'       =>'scene',
            'expire'     => 0,
            'createtime' => time(),
            'status' => 1,
            'url' => $result['url'],
            'ticket' => $result['ticket']
        );
        $insertid = db_insert('qrcode', $yx_qrcode);
        $qrcodeid = $insertid;
        $qr = array(
            'uniacid'  => $_G['mpid'],
            'acid'     => $acid,
            'useid'    => $member['useid'],
            'openid'   => $member['openid'],
            'type'     => 4,
            'scenestr' => $barcode['action_info']['scene']['scene_str'],
            'ticket'   => $result['ticket'],
            'qrimg'    => $qrimg,
            'url'      => $result['url']);
        $insertid = db_insert(t_p_ewm_permanent, $qr);
        $qr['id'] = $insertid;
        $qr['qrcodeid'] = $qrcodeid;
        $qr['current_qrimg'] = $qrimg;
        return $qr;

    }


    /**
     * 生成临时二维码
     * @param unknown $poster
     * @param unknown $member
     * @param unknown $keyword
     * @return unknown|multitype:number NULL string unknown
     */
static  function getTempQR($poster, $member,$keyword){
        global $_G;
        global $_P;
        $acid = $_G['acid'];
        $uniaccount = WeAccount::create($acid);
        $qr = db_find('select * from ' . tablename(t_ewm) . ' where 
                posterid = :posterid and themeid = :themeid and openid = :openid limit 1',
            array(':openid' =>$member['openid'],':posterid' =>$member['posterid'],':themeid' =>$member['themeid']));
        if (empty($qr) || empty($qr['scenestr']) || $qr['createtime']+ 2590000 < time()) {
            $result = self::getTempTicket($poster, $member, $uniaccount);
            if (is_error($result)) {
                return $result;
            }
            if (empty($result)) {
                return error(-1, '生成二维码失败');
            }
            $barcode = $result['barcode'];
            $ticket = $result['ticket'];
            $qrimg = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $ticket;
            $yx_qrcode = array(
                'uniacid'   => $_G['mpid'],
                'acid'      => $_G['acid'],
                'qrcid'     => $barcode['action_info']['scene']['scene_id'],
                'scene_str' => $barcode['action_info']['scene']['scene_str'],
                'model'     => 1,
                'name'      => MODULE_NAME,
                'keyword'   => $keyword,
                'type'      =>'scene',
                'expire'    => 2592000,
                'createtime'=> time(),
                'status'    => 1,
                'url'       => $result['url'],
                'ticket'    => $result['ticket']);
            $insertid = db_insert('qrcode', $yx_qrcode);
        }


        if (empty($qr)) {
            $qr = array(
                'acid'     => $acid,
                'uniacid'  => $_G['mpid'],
                'openid'   => $member['openid'],
                'themeid'  => $member['themeid'],
                'posterid' => $member['posterid'],
                'orderid'  => $member['orderid'],
                'type'     => 4,
                'scenestr' => $barcode['action_info']['scene']['scene_str'],
                'ticket'   => $result['ticket'],
                'qrimg'    => $qrimg,
                'url'      => $result['url']
            );
            $insertid = db_insert(t_ewm, $qr);
            $qr['id'] = $insertid;
            $qr['current_qrimg'] = $qrimg;
        }else if (empty($qr['scenestr']) || $qr['createtime']+2590000 < time()) {
            $data =  array(
                'scenestr' => $barcode['action_info']['scene']['scene_id'],
                'ticket'   => $result['ticket'],
                'qrimg'    => $qrimg);
            db_update(t_ewm,$data, array('id' => $qr['id']));
            $qr['current_qrimg'] = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $result['ticket'];
        }else {
            $qr['current_qrimg'] = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $qr['ticket'];
        }

        return $qr;

    }

static  function getAcidQR($acid, $openid,$keyword){
        global $_G;
        global $_P;
        $uniaccount = WeAccount::create($acid);
        $qr = db_find('select * from ' . tablename(t_ewm) . '
            where openid=:openid and acid=:acid  limit 1', array(':openid' =>$openid, ':acid' => $acid));
        if (empty($qr) || empty($qr['scenestr'])) {
            $result = getAcidTicket($acid, $uniaccount);
            if (is_error($result)) {
                return $result;
            }
            if (empty($result)) {
                return error(-1, '生成二维码失败');
            }
            $barcode = $result['barcode'];
            $ticket = $result['ticket'];
            $qrimg = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $ticket;
            $yx_qrcode = array(
                'uniacid' => $acid,
                'acid' => $acid,
                'qrcid' => $barcode['action_info']['scene']['scene_id'],
                'scene_str' => $barcode['action_info']['scene']['scene_str'],
                'model' => 1,
                'name' =>MODULE_NAME,
                'keyword' => $keyword,
                'type'=>'scene',
                'expire' => 2592000, 'createtime' => time(), 'status' => 1, 'url' => $result['url'], 'ticket' => $result['ticket']);
            $insertid = db_insert('qrcode', $yx_qrcode);
        }


        if (empty($qr)) {
            $qr = array(
                'acid' => $acid,
                'openid' =>$openid,
                'type' => 4,
                'scenestr' => $barcode['action_info']['scene']['scene_str'],
                'ticket' => $result['ticket'],
                'qrimg' => $qrimg,
                'url' => $result['url']
            );
            $insertid = db_insert(t_ewm, $qr);
            $qr['id'] = $insertid;
            $qr['current_qrimg'] = $qrimg;
        }else if (empty($qr['scenestr'])) {
            db_update(t_ewm, array('scenestr' => $barcode['action_info']['scene']['scene_id'],
                'ticket' => $result['ticket'], 'qrimg' => $qrimg), array('id' => $qr['id']));
            $qr['current_qrimg'] = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $result['ticket'];
        }else {
            $qr['current_qrimg'] = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $qr['ticket'];
        }

        return $qr;

    }

    /**
     * @describe 数组生成正则表达式
     * @param array $words
     * @return string
     */
    static function generateRegularExpression($words)
    {
        $regular = implode('|', array_map('preg_quote', $words));
        return "/$regular/i";
    }
    /**
     * @describe 字符串 生成正则表达式
     * @param array $words
     * @return string
     */
    static function generateRegularExpressionString($string){
          $str_arr[0]=$string;
          $str_new_arr=  array_map('preg_quote', $str_arr);
          return $str_new_arr[0];
    }
    /**
     * 检查敏感词
     * @param $banned
     * @param $string
     * @return bool|string
     */
    static function check_words($words,$string)
    {   
        $banned=Poster::generateRegularExpression($words);
        $match_banned=array();
        //循环查出所有敏感词
 
        $new_banned=strtolower($banned);
        $i=0;
        do{
            $matches=null;
            if (!empty($new_banned) && preg_match($new_banned, $string, $matches)) {
                $isempyt=empty($matches[0]);
                if(!$isempyt){
                    $match_banned = array_merge($match_banned, $matches);
                    $matches_str=strtolower(Poster::generateRegularExpressionString($matches[0]));
                    $new_banned=str_replace("|".$matches_str."|","|",$new_banned);
                    $new_banned=str_replace("/".$matches_str."|","/",$new_banned);
                    $new_banned=str_replace("|".$matches_str."/","/",$new_banned);
                }
            }
            $i++;
            if($i>20){
                $isempyt=true;
                break;
            }
        }while(count($matches)>0 && !$isempyt);
 
        //查出敏感词
        if($match_banned){
            return $match_banned;
        }
        //没有查出敏感词
        return array();
    }

    static function getAccessToken($system){
        global $_G;

        // $appid = $_G['platform'] ['key'];
        // $secret = $_G['platform'] ['secret'];

        $appid = $system['appidxcx'];
        $secret = $system['secretxcx'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, '');
        $c = curl_exec($ch1);
        $result = @json_decode($c, true);
        return $result['access_token'];
    }

    static function CreateXcxqr($system,$scene,$apppath)
    {

        //软件名-ID-fromuid-workerid-recordid
        // $scene = MODULE_NAME . "-" . $themeid . "-" . $uid . "-" . $theme['softkey'] ;
        // echo $scene;
        $access_token = Poster::getAccessToken($system); 
        $url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" . $access_token; 

        // $data['scene'] = $scene; 
        //小程序的详情页路径 
        $data['path'] = $apppath; 
        //二维码大小 
        $data['width'] = '430'; 

        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch1, CURLOPT_POSTFIELDS,  json_encode($data));
        $res= curl_exec($ch1);
        //load_func('file');
        $path = IA_ROOT . '/attachment/images/poster/'. date('Y-m') . '/' . MODULE_NAME.'/';
        if (!is_dir($path)) {
            mkdirs($path);
        }
        $md5 = md5(json_encode($apppath.$scene.TIMESTAMP));
        $file = $md5 . '.png';
        file_put_contents($path.$file, $res);
        $posterimg = 'images/poster/'. date('Y-m') . '/' . MODULE_NAME.'/' . $file;

        $remotestatus = file_remote_upload($posterimg); //上传图片到远程
        if (is_error($remotestatus)) { 
            return_msg(1, '生成海报上传失败');
            exit;
        } else {
            $qrimg = tomedia($posterimg);  // 远程图片的访问URL
        }
        return $qrimg;
    }

    static function CreateScene($system,$scene,$apppath)
    {

        //软件名-ID-fromuid-workerid-recordid
        // $scene = MODULE_NAME . "-" . $themeid . "-" . $uid . "-" . $theme['softkey'] ;
        // echo $scene;
        $access_token = Poster::getAccessToken($system); 
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token; 

        $data['scene'] = $scene; 
        //小程序的详情页路径 
        $data['page'] = $apppath; 
        //二维码大小 
        $data['width'] = '430'; 

        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch1, CURLOPT_POSTFIELDS,  json_encode($data));
        $res= curl_exec($ch1);
        //load_func('file');
        $path = IA_ROOT . '/attachment/images/poster/'. date('Y-m') . '/' . MODULE_NAME.'/';
        if (!is_dir($path)) {
            mkdirs($path);
        }
        $md5 = md5(json_encode($apppath.$scene.TIMESTAMP));
        $file = $md5 . '.png';
        file_put_contents($path.$file, $res);
        $posterimg = 'images/poster/'. date('Y-m') . '/' . MODULE_NAME.'/' . $file;

        $remotestatus = file_remote_upload($posterimg); //上传图片到远程
        if (is_error($remotestatus)) { 
            return_msg(1, '生成海报上传失败');
            exit;
        } else {
            $qrimg = tomedia($posterimg);  // 远程图片的访问URL
        }
        return $qrimg;
    }

    static function getContentvideoimg($contentvideo)
    {
        //获取富文本中的图片和视频转为数组
        $contentvideo = str_replace("&nbsp;","",$contentvideo);//将空格替换成空
        $contentvideo = strip_tags($contentvideo, '<img><video>');
        $contentvideo=explode('<video',$contentvideo);
        // var_dump($contentvideo);
        $content = array();
        if (!empty($contentvideo)) {
            foreach ($contentvideo as $index => $item) {
                $posterurl='';$video='';$posterheight=500;
                $end = strpos($item,"\" class=\"edui-upload");
                if ($end>0 ) {
                    $isposter = strpos($item,"/resource/images/player.jpg");
                    if ($isposter==0) {
                        $posterurl = substr($item, 9, $end-9);
                        $img_info = getimagesize($posterurl);
                        if (!empty($img_info[0]) && !empty($img_info[1])) {
                            $posterheight=intval($img_info[1]/($img_info[0]/750));
                        }else{
                            $posterheight=500;
                        }

                    }
                    $start = strpos($item,"\"auto\" src=\"")+12;
                    $end = strpos($item,"\" data-setup=");
                    if ($start>0 && $end-$start>0) {
                        $video = substr($item, $start, $end-$start);
                    }               
                }
                if (!empty($video)) {
                    array_push($content, array('type' =>'video' ,'url' =>$video ,'poster'=>$posterurl ,'posterheight'=>$posterheight ));
                }
                preg_match_all('/\<img\s+src\=\"([\w:\/\.]+)\"/', $item, $matches);
                if (!empty($matches[1])) {
                    foreach ($matches[1] as $index => $item) {
                        array_push($content, array('type' =>'img' ,'url' =>$item ));
                    }
                }
            }
        }
        return $content;
    }


}


